package com.sanhuo;

import com.sanhuo.triild.Session;
import com.sanhuo.utils.basic.BeanUtil;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import static com.sanhuo.triild.utils.AnnotationUtil.isDaoMethod;

public class MapperProxy implements InvocationHandler {
    private Session session = new Session();
    private Class interfes;


    @SuppressWarnings("unchecked")
    public static <T> T ProxyFactory(Class<T> clazz) {
        MapperProxy proxy = new MapperProxy();
        proxy.setInterfes(clazz);
        Object result = Proxy.newProxyInstance(clazz.getClassLoader(), new Class[]{clazz}, proxy);
        return (T) result;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        Class clazz = proxy.getClass();
        Type[] types = interfes.getGenericInterfaces();
        if (types.length == 0 || !BeanUtil.isNotNull(types[0])) {
            List<Type> typeList = new ArrayList<>();
            typeList.add(new Type() {
                @Override
                public String getTypeName() {
                    return null;
                }
            });
            types = typeList.toArray(new Type[0]);
        }
        if (isDaoMethod(method)) {
            return session.excute(method, args, types[0]);
        }
        return null;

    }

    public Class getInterfes() {
        return interfes;
    }

    public void setInterfes(Class interfes) {
        this.interfes = interfes;
    }

}
